import { Injectable } from '@nestjs/common';
import { CreateQuoteDto } from './dto/create-quote.dto';
import { UpdateQuoteDto } from './dto/update-quote.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Quote } from './entities/quote.entity';
import { Repository } from 'typeorm';
import { ResponseService } from 'src/response/response.service';
import { SimplePaginatedResponse } from 'src/common/dto/pagination.dto';

@Injectable()
export class QuoteService {
  constructor(
    @InjectRepository(Quote) private readonly quote: Repository<Quote>,
    private readonly responseService: ResponseService,
  ) {}

  create(createQuoteDto: CreateQuoteDto) {
    return 'This action adds a new quote';
  }

  async findAll() {
    const quote = await this.quote.find({
      order: {
        date: 'DESC',
      },
      relations: ['supplier', 'productinfo', 'productinfo.msbmanages'],
    });
    return {
      quote,
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} quote`;
  }

  update(id: number, updateQuoteDto: UpdateQuoteDto) {
    return `This action updates a #${id} quote`;
  }

  remove(id: number) {
    return `This action removes a #${id} quote`;
  }

  async searchByKeyword(
    keyword: string,
    page: number = 1,
    limit: number = 50,
  ): Promise<SimplePaginatedResponse<Quote>> {
    const pageNum = Math.max(1, Math.min(page, 2147483647));
    const pageSize = Math.max(1, Math.min(limit, 1000));
    const skip = (pageNum - 1) * pageSize;

    const [data, total] = await this.quote
      .createQueryBuilder('quote')
      .leftJoinAndSelect('quote.supplier', 'supplier')
      .leftJoinAndSelect('quote.productinfo', 'productinfo')
      .leftJoinAndSelect('productinfo.msbmanages', 'msbmanage')
      .where('productinfo.productname LIKE :keyword', {
        keyword: `%${keyword}%`,
      })
      .orWhere('productinfo.productcode LIKE :keyword', {
        keyword: `%${keyword}%`,
      })
      .orWhere('msbmanage.msbmanageidcode LIKE :keyword', {
        keyword: `%${keyword}%`,
      })
      .orderBy('quote.date', 'DESC')
      .take(pageSize)
      .skip(skip)
      .getManyAndCount();

    return {
      data,
      total,
      page: pageNum,
      limit: pageSize,
    };
  }
}
